package com.imay.live.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.fragment.BaseFragment;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.adapter.ProfileSendGiftRankingAdapter;
import com.imay.live.adapter.RankingAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.model.ProfileRankingSendGiftModel;
import com.imay.live.model.RankingModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * 排行榜
 */
public class SendGiftRankingFragment extends BaseRequestFragment  {


    private RecyclerView rcv_send_gift_ranking;
    private ProfileSendGiftRankingAdapter sendGiftRankingAdapter;
    private IMYTBASObject loadGiftListener;
    private TwinklingRefreshLayout trl_refresh_profile_ranking;
    private String sendGiftCommand;
    private long maxId;
    private int count=30;
    private List<ProfileRankingSendGiftModel> rankingModelList;

    public static SendGiftRankingFragment newInstance() {
        SendGiftRankingFragment fragment = new SendGiftRankingFragment();
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_send_gift_ranking;
    }

    @Override 
    protected void initView(Bundle savedInstanceState) {
        bindViews();
        registerGiftNotify();
        rankingModelList = new ArrayList<>();
        loadData();
        MobclickAgent.onEvent(getActivity(),"gift_open_give");

    }

    private void bindViews() {
        rcv_send_gift_ranking= $(R.id.rcv_send_gift_ranking);
        trl_refresh_profile_ranking= $(R.id.trl_refresh_profile_ranking);
            rcv_send_gift_ranking.setLayoutManager(new LinearLayoutManager(getActivity()));
            RefreshView headerView = new RefreshView(getActivity());
            trl_refresh_profile_ranking.setHeaderView(headerView);
            trl_refresh_profile_ranking.setBottomView(new LoadingView(getActivity()));
            trl_refresh_profile_ranking.setEnableLoadmore(true);
            trl_refresh_profile_ranking.setEnableOverScroll(false);
            trl_refresh_profile_ranking.setOnRefreshListener(new RefreshListenerAdapter() {
                @Override
                public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                    maxId=0;
                    loadData();
                }

                @Override
                public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                    loadMore();
                }
            });

    }


    public void bindAdapter(){
        if (sendGiftRankingAdapter==null){
            sendGiftRankingAdapter = new ProfileSendGiftRankingAdapter(rankingModelList);
            rcv_send_gift_ranking.setAdapter(sendGiftRankingAdapter);
            sendGiftRankingAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout,null));
            sendGiftRankingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ProfileActivity.start(getActivity(),sendGiftRankingAdapter.getData().get(position).getToUser().getUid());
                }
            });
        }else {
            sendGiftRankingAdapter.setNewData(rankingModelList);
            sendGiftRankingAdapter.notifyDataSetChanged();
        }
        trl_refresh_profile_ranking.setEnableLoadmore(!rankingModelList.isEmpty());


    }



    protected void registerGiftNotify() {
        loadGiftListener = new IMYTBASObject(true);
        loadGiftListener.stringCommand = EventHelper.EVENT_GIFT_LOADED;
        loadGiftListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                if (sendGiftRankingAdapter!=null&&getActivity()!=null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendGiftRankingAdapter.notifyDataSetChanged();
                        }
                    });
                }

            }
        });
        loadGiftListener.addEventListenWithTBASObject();

    }

    @Override
    public void onDestroy() {
        if (loadGiftListener != null) {
            loadGiftListener.destroy();
        }
        super.onDestroy();

    }

    private void loadData(){
            sendGiftCommand = ProtoRequestHelper.task(ProtoHttpFactory.getProfileSendGiftRanking(maxId, count)).setTag(this.hashCode()).request(this);
    }
    private void loadMore(){
        if (rankingModelList.isEmpty()){
            return;
        }
        maxId = rankingModelList.get(rankingModelList.size()-1).getId();
        loadData();
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        if (command.equals(sendGiftCommand)){
            Result<List<ProfileRankingSendGiftModel>> result = JSON.parseObject(data, new TypeReference<Result<List<ProfileRankingSendGiftModel>>>() {}.getType());
            if (result.result == CodeSuccess) {
                rankingModelList.addAll(result.data);
                bindAdapter();
            }
        }
        refreshFinish();
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        refreshFinish();

    }

    private void refreshFinish() {
        if (trl_refresh_profile_ranking != null) {
            if (maxId==0){
                trl_refresh_profile_ranking.finishRefreshing();
            }else{
                trl_refresh_profile_ranking.finishLoadmore();
            }
        }
    }
    boolean isCreated;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isCreated){
            if (isVisibleToUser) {
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }
        }
    }
}
